﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.IO.Packaging;

namespace MouseExtender.Archiver
{
	class Program
	{
		private const string sourceFolderPath = "updates";

		static void Main(string[] args)
		{
			DirectoryInfo rootUpdatesFolder = new DirectoryInfo(sourceFolderPath);

			ZipPackage package = (ZipPackage)ZipPackage.Open("MouseExtender.zip", FileMode.Create, FileAccess.ReadWrite);
			CreatePackageParts(package, rootUpdatesFolder, "/");

			foreach (ZipPackagePart part in package.GetParts().ToList())
			{
				package.CreateRelationship(part.Uri, TargetMode.Internal, "http://schemas.microsoft.com/xps/2005/06/required-resource");
			}
			package.Flush();
			package.Close();
		}

		private static void CreatePackageParts(ZipPackage package, DirectoryInfo folder, string folderUri)
		{
			foreach (DirectoryInfo subFolder in folder.GetDirectories())
			{
				string subFolderUri = folderUri + subFolder.Name + "/";
				CreatePackageParts(package, subFolder, subFolderUri);
			}

			foreach (FileInfo file in folder.GetFiles())
			{
				Uri partUri = new Uri(folderUri + file.Name, UriKind.Relative);
				ZipPackagePart part = (ZipPackagePart)package.CreatePart(partUri, GetContentType(file.Name), CompressionOption.NotCompressed);
				using (Stream fs = file.OpenRead(), ps = part.GetStream(FileMode.Open, FileAccess.Write))
				{
					StreamHelper.CopyStream(fs, ps);
					ps.Flush();
				}
			}
		}

		private static string GetContentType(string fileName)
		{
			string extension = Path.GetExtension(fileName);
			string contentType = null;
			switch (extension.ToLower())
			{
				case ".exe":
				case ".dll":
				case ".pdb":
					{
						contentType = "application/octet-stream";
						break;
					}
				case ".bat":
					{
						contentType = "application/bat";
						break;
					}
				case ".txt":
				case ".log":
					{
						contentType = "text/plain";
						break;
					}
				case ".xml":
				case ".cfg":
					{
						contentType = "text/xml";
						break;
					}
			}

			return contentType;
		}
	}
}
